<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col>
          <div>
            <el-button type="primary" plain @click="showAddAccountModalHandler">添加系统账号</el-button>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            class="mt-20"
            :header-row-class-name="
              ({ row, rowIndex }) => {
                if (rowIndex === 0) return 'table-header-bg'
              }
            "
          >
            <el-table-column type="index" width="80" label="序号"> </el-table-column>
            <el-table-column prop="adminName" label="用户账号"> </el-table-column>
            <el-table-column prop="adminPhone" label="手机号码"> </el-table-column>
            <el-table-column prop="adminEmail" label="Ema邮箱"> </el-table-column>
            <el-table-column prop="roleId" label="角色名称">
              <template v-slot="scope">
                {{ getRoleName(scope.row.roleId) }}
              </template>
            </el-table-column>
            <el-table-column prop="state" label="用户状态">
              <template v-slot="scope">
                <span v-if="scope.row.adminState === 1 || scope.row.adminState === -1" class="text-success">
                  正常
                </span>
                <span
                  v-else-if="scope.row.adminState === 0"
                  class="text-danger cursor-hand"
                  @click="deleteAccountFn(scope.row)"
                >
                  启用(deleted)
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template v-slot="scope">
                <i
                  v-if="scope.row.adminState !== 999"
                  class="text-20 mr-20 curser-pointer text-warning el-icon-edit"
                  @click="modifyAccountFn(scope.row)"
                ></i>
                <el-popconfirm
                  v-if="scope.row.adminState !== 999"
                  confirm-button-text="删除"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定要删除这个账号吗？"
                  @confirm="deleteAccountFn(scope.row)"
                >
                  <i slot="reference" class="text-20 mr-20 curser-pointer text-danger el-icon-delete"></i>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="py-20">
        <el-col :span="24" class="text-left">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="currentChangeHandler"
            :total="total"
            :current-page="nowPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-col>
    <el-dialog
      :destory-on-close="true"
      title="修改系统账号"
      :visible.sync="modalVisible2"
      width="30%"
      @close="handler_close2"
    >
      <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="120px">
        <el-form-item label="账号名称" prop="adminName">
          <el-input v-model="ruleForm2.adminName" placeholder="请输入系统用户名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="adminEmail">
          <el-input v-model="ruleForm2.adminEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="adminPhone">
          <el-input v-model="ruleForm2.adminPhone" placeholder="请输入手机号码,密码默认是手机号码后6位"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleId">
          <el-select v-model="ruleForm2.roleId" placeholder="请选择角色">
            <!-- <el-option value="0" disabled>请选择角色</el-option> -->
            <el-option
              v-for="item in roleList"
              v-bind:key="item.roleId"
              :value="item.roleId"
              :label="item.roleName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="updateAccountFn('ruleForm2')">修改</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :destory-on-close="true"
      title="添加系统账号"
      :visible.sync="modalVisible"
      width="30%"
      @close="handler_close"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="账号名称" prop="adminName">
          <el-input v-model="ruleForm.adminName" placeholder="请输入系统用户名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="adminEmail">
          <el-input v-model="ruleForm.adminEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="adminPhone">
          <el-input
            @input="checkPhoneHandler"
            v-model="ruleForm.adminPhone"
            placeholder="请输入手机号码,密码默认是手机号码后6位"
          ></el-input>
          <span v-if="phoneIsRegister !== ''">{{ phoneIsRegister === false ? '未使用' : '已注册' }}</span>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleId">
          <el-select v-model="ruleForm.roleId" placeholder="请选择角色">
            <!-- <el-option value="0" disabled>请选择角色</el-option> -->
            <el-option
              v-for="item in roleList"
              v-bind:key="item.roleId"
              :value="item.roleId"
              :label="item.roleName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible = false">取 消</el-button>
        <el-button v-if="phoneIsRegister === false" type="primary" @click="addAccountFn('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
import { getRoleAll, addAccount, modifyAccount, editAccountState, checkPhone, queryPageAccount } from './../config/api'
export default {
  data() {
    return {
      pageSize: 5,
      nowPage: 1,
      total: 0,
      pageSizes: [5, 10, 20, 50],
      modalVisible: false,
      modalVisible2: false,
      roleList: [],
      ruleForm: {
        adminName: '',
        adminEmail: '',
        adminPhone: '',
        roleId: undefined
        // adminId: '', //添加不要
        // state: true //添加不要
      },
      rules: {
        adminName: [
          { required: true, message: '请输入系统用户名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        adminEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        adminPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请选择系统用户角色', trigger: 'change' }]
      },
      ruleForm2: {
        adminName: '',
        adminEmail: '',
        adminPhone: '',
        roleId: undefined,
        adminId: undefined,
        state: true
      },
      rules2: {
        adminName: [
          { required: true, message: '请输入系统用户名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        adminEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        adminPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请选择系统用户角色', trigger: 'change' }]
      },
      tableData: [
        {
          adminName: 'wen1',
          adminEmail: '1214@qq.com',
          adminPhone: '15464654641',
          roleId: 1,
          adminId: 100,
          state: 1
        },
        {
          adminName: 'wen2',
          adminEmail: '1214@qq.com',
          adminPhone: '15464654641',
          roleId: 2,
          adminId: 111,
          state: 0
        }
      ],
      phoneIsRegister: ''
    }
  },
  created() {
    this.getRoleFindAll() //获取角色
    this.getAccountPageFn() // 获取所有账号
  },
  methods: {
    // 验证手机号码是否被注册
    checkPhoneHandler() {
      let phone = this.ruleForm.adminPhone
      if (/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
        checkPhone({ phone }).then(res => {
          if (res.code === 200) {
            if (res.data === false) {
              this.phoneIsRegister = false
            } else {
              this.phoneIsRegister = true
            }
          } else {
            this.$message({
              type: 'success',
              message: '检查手机号码是否被注册失败！'
            })
            this.phoneIsRegister = ''
          }
        })
      } else {
        this.phoneIsRegister = ''
      }
    },
    // 获取角色名称
    getRoleName(roleId) {
      let roleName = ''
      this.roleList.forEach(el => {
        if (el.roleId === roleId) {
          roleName = el.roleName
        }
      })
      return roleName
    },
    getRoleFindAll() {
      getRoleAll().then(res => {
        if (res.code === 200) {
          console.log(res.data)
          this.roleList = res.data
        } else {
          this.$message({
            message: '查询角色列表失败，请联系管理员'
          })
        }
      })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.getAccountPageFn()
    },
    currentChangeHandler(page) {
      // console.log(page)
      this.nowPage = page
      this.getAccountPageFn()
    },
    // 更新数据函数, waiting....
    updateAccountFn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(valid)

          modifyAccount(this.ruleForm2).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '修改用户信息成功'
              })
              this.modalVisible2 = false
              this.getAccountPageFn()
            } else {
              this.$message({
                type: 'error',
                message: '修改用户信息失败'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 显示添加用户modal
    showAddAccountModalHandler() {
      this.modalVisible = true
    },
    // 显示修改的模态框
    modifyAccountFn(row) {
      this.modalVisible2 = true
      this.ruleForm2 = Object.assign({}, row) // 两个对象还是引用的关系
      // console.log(this.ruleForm2)
    },
    // 添加系统用户
    addAccountFn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addAccount(this.ruleForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '添加系统用户成功'
              })
              // this.$refs[formName].resetFields() // 重置表单，避免打开modal是，触发验证,可在@close里面统一实现
              this.getAccountPageFn()
              this.modalVisible = false
            } else {
              this.$message({
                type: 'error',
                message: '添加系统用户失败'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除用户，修改用户状态为禁用或者正常
    deleteAccountFn({ adminId, adminState }) {
      console.log('delete:', adminId, adminState)
      let s = adminState === 1 ? 0 : 1
      let params = { adminId, state: s }
      console.log(params)
      editAccountState(params).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除系统用户成功'
          })
          this.getAccountPageFn() // 获取一页数据
        } else {
          this.$message({
            type: 'success',
            message: '删除系统用户失败'
          })
        }
      })
    },
    // 获取所有用户数据，waiting....
    // getAccountList() {},
    // 分页获取所有用户数据，waiting....
    getAccountPageFn() {
      queryPageAccount({ pageNum: this.nowPage, pageSize: this.pageSize }).then(res => {
        if (res.code === 200) {
          console.log('users:', res.data)
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },

    // 关闭时，重置表单，避免触发验证
    handler_close() {
      console.log('close modal')
      this.$refs['ruleForm'].resetFields()
    },
    // 关闭时，重置表单，避免触发验证
    handler_close2() {
      console.log('close modal')
      this.$refs['ruleForm2'].resetFields()
    }
  }
}
</script>

<style>
.water-meter-item {
  border: 1px solid rgb(199, 197, 197);
  border-radius: 3px;
  margin: 10px;
  padding: 10px;
}
.water-meter-item > p {
  color: gray;
}
.bg-layer-top {
  background-color: rgb(209, 189, 203);
}
.bg-layer-body {
  background-color: rgb(224, 215, 215);
  border: 1px solid rgb(208, 202, 209);
}
.kf-label {
  display: inline-block;
  line-height: 40px;
  /* width: 120px;
  text-align: right; */
  margin-right: 10px;
  color: grey;
}
.table-header {
  background-color: rgb(100, 67, 100);
}
.cursor-hand {
  cursor: pointer;
}
</style>
